package cn.conac.rc.ofs.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.framework.utils.BeanMapper;
import cn.conac.rc.ofs.contsant.Contsants;
import cn.conac.rc.ofs.entity.DepartmentEntity;
import cn.conac.rc.ofs.entity.DepartmentEntity2;
import cn.conac.rc.ofs.entity.DutyEntity;
import cn.conac.rc.ofs.repository.DepartmentRepository;
import cn.conac.rc.ofs.repository.DepartmentRepository2;
import cn.conac.rc.ofs.vo.DepartmentTreeNodeVo;
import cn.conac.rc.ofs.vo.DepartmentTreeNodeVo2;
import cn.conac.rc.ofs.vo.DepartmentVo;

@Service
public class DepartmentService extends GenericService<DepartmentEntity, Integer> {

	@Autowired
	private DepartmentRepository repository;
	
	@Autowired
	private DepartmentRepository2 repository2;

	/**
	 * 计数查询
	 * 
	 * @param vo
	 * @return 计数结果
	 */
	public long count(DepartmentVo vo) {
		return super.count(this.createCriteria(vo));
	}

	/**
	 * 动态查询，分页，排序查询
	 * 
	 * @param vo
	 * @return Page
	 * @throws Exception
	 */
	public Page<DepartmentEntity> list(DepartmentVo vo) throws Exception {
		try {
			Sort sort = new Sort(Direction.ASC, "id");// TODO 可选的排序
			Pageable pageable = new PageRequest(vo.getPage(), vo.getSize(), sort);
			Criteria<DepartmentEntity> dc = this.createCriteria(vo);
			return repository.findAll(dc, pageable);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 动态查询条件
	 * 
	 * @param param
	 * @return Criteria
	 */
	private Criteria<DepartmentEntity> createCriteria(DepartmentVo param) {
		Criteria<DepartmentEntity> dc = new Criteria<DepartmentEntity>();
		// TODO 具体条件赋值

		return dc;
	}

	/**
	 * 根据baseId查询该机构的所有内设机构信息(并按照内设顺序号升序排序)
	 * 
	 * @param baseId
	 * @return DutyEntity的List
	 */
	public List<DepartmentEntity> findByBaseId(Integer baseId) {
		return repository.findByBaseIdOrderByDepNumAsc(baseId);
	}
	
	/**
	 * 根据baseId查询该机构的所有内设机构信息(并按照内设顺序号升序排序)
	 * @param baseId
	 * @return  内设机构Tree
	 */
	public List<DepartmentEntity> findLevelFlagsByBaseIdOpt(Integer baseId) {
		// 虚拟实例化组织架构中的最顶端的内设机构
		DepartmentTreeNodeVo rootDeptTreeNode = new DepartmentTreeNodeVo();
		rootDeptTreeNode.setId("01");
		rootDeptTreeNode.setName("内设机构");
		List<DepartmentEntity> convertDeptInfoList = new ArrayList<DepartmentEntity>();
		Map<String, DepartmentTreeNodeVo> deptTreeNodeMap = new HashMap<String, DepartmentTreeNodeVo>();
		DepartmentTreeNodeVo departmentTreeNodeVo = null;
		Integer parentId = null;
		List<DepartmentEntity> departmentListOpt  = repository.findByBaseId(baseId);
		for(DepartmentEntity departmentEntity: departmentListOpt) {
			departmentTreeNodeVo = new DepartmentTreeNodeVo(departmentEntity);
			deptTreeNodeMap.put(departmentTreeNodeVo.getId().toString(), departmentTreeNodeVo);
		}
		for (DepartmentTreeNodeVo deptTreeNode : deptTreeNodeMap.values()) {
			parentId = deptTreeNode.getParentId();
			// 过滤掉递归无限循环的异常情况（内设机构id和parentId是相同的）
			if(deptTreeNode.getId().equals(parentId)) {
				continue;
			}
			if(parentId.intValue() == -1) {
				rootDeptTreeNode.addChild(deptTreeNode);
			} else {
				if (null != parentId && deptTreeNodeMap.containsKey(parentId.toString())) {
					deptTreeNodeMap.get(parentId.toString()).addChild(deptTreeNode);
				}
			}
		}
		receiveSortDeptList(rootDeptTreeNode.getChildren());
		receiveSetDeptDisplayName(rootDeptTreeNode.getChildren(), 0, convertDeptInfoList);
		
		return convertDeptInfoList;
	}
	
	/**
	 * 递归设置内设机构的层级
	 * @param deptTreeNodeList
	 * @return
	 */
	private  List<DepartmentTreeNodeVo> receiveSetDeptDisplayName(List<DepartmentTreeNodeVo> deptTreeNodeList, 
			Integer deptLevel, List<DepartmentEntity>  convertDeptInfoList) {
		if (null == deptTreeNodeList || deptTreeNodeList.isEmpty()) {
			return new ArrayList<DepartmentTreeNodeVo>();
		}
		deptLevel  += 1;
		String levelFlagStr="";
	    for(int i = 1;  i < deptLevel;  i++){
	    	levelFlagStr += Contsants.DEPT_ONE_LEVEL_FLAG;
	    }
		// 递归排序
	    DepartmentEntity departmentEntity = null;
		for (DepartmentTreeNodeVo deptTreeNodeVo : deptTreeNodeList) {
			departmentEntity = new DepartmentEntity();
			BeanMapper.copy(deptTreeNodeVo, departmentEntity);
			departmentEntity.setDisplayName(levelFlagStr + deptTreeNodeVo.getDeptName());
			convertDeptInfoList.add(departmentEntity);
			receiveSetDeptDisplayName(deptTreeNodeVo.getChildren(), deptLevel,convertDeptInfoList);
		}
		return deptTreeNodeList;
	}
	
	/**
	 * 根据职能职责ID获取对应部门信息
	 * 
	 * @param dutyId
	 * @return DepartmentEntity的List
	 */
	public List<DepartmentEntity> findByDutyId(Integer dutyId) {
		return repository.findByDutyId(dutyId);
	}
	
	/**
	 * 根据部门库Id获取没有关联职能职责的内设机构
	 * 
	 * @param id
	 * @return DepartmentEntity的List
	 */
	public List<DepartmentEntity> finddeptWithNoDeptListByOrgId(Integer id) {
		return repository.finddeptWithNoDeptListByOrgId(id);
	}
	
	/**
	 * 复制旧BaseId对应的内设部门到新的内设部门
	 * @param oldBaseId
	 * @param newBaseId
	 * @return List<DepartmentEntity>
	 */
	public List<DepartmentEntity> copyDepartmentInfo(Integer oldBaseId, Integer newBaseId, List<DutyEntity> dutyList){
		// 通过oldBaseId获取内设机构信息
		List<DepartmentEntity> oldDepartmentList = repository.findByBaseIdOrderByDepNumAsc(oldBaseId);
		// 判断为空
		if(oldDepartmentList == null){
			return null;
		}
		List<DepartmentEntity> newDepartmentList = new ArrayList<>();
		// 循环复制内设机构到新的内设机构信息中
		for(DepartmentEntity oldDepart : oldDepartmentList){
			DepartmentEntity newDepart = new DepartmentEntity();
			BeanMapper.copy(oldDepart, newDepart);
			newDepart.setId(null);
			newDepart.setBaseId(newBaseId);
			newDepart.setOldId4Copy(oldDepart.getId());
			// 复制职能职责
			List<DutyEntity> dList = oldDepart.getDutyList();
			List<DutyEntity> newDList = new ArrayList<>();
			if(dList != null && dList.size() != 0 && dutyList != null && dutyList.size() != 0){
				for(DutyEntity d: dList){
					for(DutyEntity duty: dutyList){
						if(duty.getOldId4Copy().equals(d.getId())){
							newDList.add(duty);
						}
					}
				}
			}
			newDepart.setDutyList(newDList);

			newDepartmentList.add(repository.save(newDepart));
		}
		// 内设机构上级ID设定
		for(DepartmentEntity newDepart : newDepartmentList){
			for(DepartmentEntity newDepartInner : newDepartmentList){
				if(newDepart.getParentId() != null &&
						newDepart.getParentId().equals(newDepartInner.getOldId4Copy())){
					newDepart.setParentId(newDepartInner.getId());
				}
			}
			repository.save(newDepart);
		}
		return newDepartmentList;
	}

	/**
	 * 复制旧BaseId对应的内设部门到新的内设部门
	 * @param departIds
	 * @param baseId
	 * @return List<DepartmentEntity>
	 */
	public List<DepartmentEntity> copyDepartmentInfoWithDepartIds(List<String> departIds, Integer baseId){

		List<DepartmentEntity> departmentList = new ArrayList<>();
		for(String departId:departIds) {
			// 通过departId获取内设机构信息
			DepartmentEntity departEntity = repository.findOne(new Integer(departId));

			DepartmentEntity newDepart = new DepartmentEntity();
			BeanMapper.copy(departEntity, newDepart);
			newDepart.setId(null);
			newDepart.setBaseId(baseId);
			newDepart.setParentId(-1);
			newDepart.setOldId4Copy(departEntity.getId());
			departmentList.add(repository.save(newDepart));
		}

		return departmentList;
	}
	
	/**
	 * 根据baseId查询该机构的一级内设机构信息并包含是否含有子内设Flag信息(并按照内设顺序号升序排序)
	 * 返回实体DepartmentVo的属性childFlag的值大于0时表示该内设有子内设，等于0表示没有
	 * @param baseId
	 * @return 内设机构List
	 */
	public List<DepartmentVo> findLevelOneByBaseId(Integer baseId){
		List<DepartmentEntity> departmentList  = repository.findLevelOneByBaseId(baseId);
		List<DepartmentVo> departmentVoList = new ArrayList<DepartmentVo>();
		DepartmentVo departmentVo =null;
		List<DepartmentEntity> subDepartmentList  = new ArrayList<DepartmentEntity>();
		for(DepartmentEntity departmentEntity: departmentList){
			departmentVo =new DepartmentVo();
			BeanMapper.copy(departmentEntity, departmentVo);
			subDepartmentList = repository.findByParentId(departmentEntity.getId());
			departmentVo.setChildFlag(subDepartmentList.size());
			departmentVoList.add(departmentVo);
		}
		return departmentVoList;
	}
	
	/**
	 * 根据parentId查询该机构的一级内设机构信息(并按照内设顺序号升序排序)
	 * @param parentId
	 * @return 内设机构List
	 */
	public List<DepartmentEntity> findByParentIdOrderByDepNumAsc(Integer parentId){
		return repository.findByParentIdOrderByDepNumAsc(parentId);
	}
	
	/**
	 * 根据baseId查询该机构的所有内设机构信息(并按照内设顺序号升序排序)
	 * @param baseId
	 * @param mapTree
	 * @param flag (1: App内设机构使用  2：三定组织架构图使用)
	 * @return 一级内设机构List
	 */
	public DepartmentTreeNodeVo2 findMapTreeByBaseIdOpt(Integer baseId) {
		// 虚拟实例化组织架构中的最顶端的内设机构
		DepartmentTreeNodeVo2 rootDeptTreeNode = new DepartmentTreeNodeVo2();
		rootDeptTreeNode.setId("01");
		rootDeptTreeNode.setName("内设机构");
		// 顶端的内设机构不可点击因此设置hrefFlag的标示为"0"
		rootDeptTreeNode.setHrefFlag("0");
		
		Map<String, DepartmentTreeNodeVo2> deptTreeNodeMap = new HashMap<String, DepartmentTreeNodeVo2>();
		DepartmentTreeNodeVo2 departmentTreeNodeVo = null;
		Integer parentId = null;
		List<DepartmentEntity2> departmentListOpt  = repository2.findByBaseId(baseId);
		for(DepartmentEntity2 departmentEntity2: departmentListOpt) {
			departmentTreeNodeVo = new DepartmentTreeNodeVo2(departmentEntity2, "1");
			deptTreeNodeMap.put(departmentTreeNodeVo.getId(), departmentTreeNodeVo);
		}
		for (DepartmentTreeNodeVo2 deptTreeNode : deptTreeNodeMap.values()) {
			parentId = deptTreeNode.getParentId();
			// 过滤掉递归无限循环的异常情况（内设机构id和parentId是相同的）
			if(deptTreeNode.getId().equals(parentId)) {
				continue;
			}
			if(parentId.intValue() == -1) {
				rootDeptTreeNode.addChild(deptTreeNode);
			} else {
				if (null != parentId && deptTreeNodeMap.containsKey(parentId.toString())) {
					deptTreeNodeMap.get(parentId.toString()).addChild(deptTreeNode);
				}
			}
		}
		receiveSortDeptList2(rootDeptTreeNode.getChildren());
		return rootDeptTreeNode;
	}
	
	/**
	 * 根据baseId查询该机构的所有内设机构信息(并按照内设顺序号升序排序)
	 * @param baseId
	 * @return  内设机构Tree
	 */
	public DepartmentTreeNodeVo2 findMapListByBaseIdOpt(Integer baseId) {
		// 虚拟实例化组织架构中的最顶端的内设机构
		DepartmentTreeNodeVo2 rootDeptTreeNode = new DepartmentTreeNodeVo2();
		rootDeptTreeNode.setId("01");
		rootDeptTreeNode.setName("内设机构");
		// 设置总节点的层级为0
		rootDeptTreeNode.setLevel(0);
		
		Map<String, DepartmentTreeNodeVo2> deptTreeNodeMap = new HashMap<String, DepartmentTreeNodeVo2>();
		DepartmentTreeNodeVo2 departmentTreeNodeVo = null;
		Integer parentId = null;
		List<DepartmentEntity2> departmentListOpt  = repository2.findByBaseId(baseId);
		for(DepartmentEntity2 departmentEntity2: departmentListOpt) {
			departmentTreeNodeVo = new DepartmentTreeNodeVo2(departmentEntity2);
			deptTreeNodeMap.put(departmentTreeNodeVo.getId(), departmentTreeNodeVo);
		}
		for (DepartmentTreeNodeVo2 deptTreeNode : deptTreeNodeMap.values()) {
			parentId = deptTreeNode.getParentId();
			// 过滤掉递归无限循环的异常情况（内设机构id和parentId是相同的）
			if(deptTreeNode.getId().equals(parentId)) {
				continue;
			}
			if(parentId.intValue() == -1) {
				rootDeptTreeNode.addChild(deptTreeNode);
			} else {
				if (null != parentId && deptTreeNodeMap.containsKey(parentId.toString())) {
					deptTreeNodeMap.get(parentId.toString()).addChild(deptTreeNode);
				}
			}
		}
		//recursiveSetLevel(rootDeptTreeNode.getChildren());
		receiveSetDeptLevel2(rootDeptTreeNode.getChildren(), 0);
		receiveSortDeptList2(rootDeptTreeNode.getChildren());
		return rootDeptTreeNode;
	}
	
	/**
	 * 递归设置内设机构的层级
	 * @param deptTreeNodeList
	 * @return
	 */
	private  List<DepartmentTreeNodeVo2> receiveSetDeptLevel2(List<DepartmentTreeNodeVo2> deptTreeNodeList, Integer deptLevel) {
		if (null == deptTreeNodeList || deptTreeNodeList.isEmpty()) {
			return new ArrayList<DepartmentTreeNodeVo2>();
		}
		deptLevel  += 1;
		// 递归排序
		for (DepartmentTreeNodeVo2 deptTreeNodeVo : deptTreeNodeList) {
			deptTreeNodeVo.setLevel(deptLevel);
			receiveSetDeptLevel2(deptTreeNodeVo.getChildren(), deptLevel);
		}
		return deptTreeNodeList;
	}

	/**
	 * 根据parentId查询该机构的一级内设机构信息(并按照内设顺序号升序排序)
	 * @param baseId
	 * @return 内设机构List
	 */
	public int findMaxDepNum(Integer baseId){
		return repository.findMaxDepNumByOrgId(baseId);
	}
	
	
	/**
	 * 根据baseID和parentID获取对应部门信息列表
	 * 
	 * @param baseId
	 * @param parentId
	 * @return DepartmentEntity的List
	 */
	public List<DepartmentEntity> findByBIdAndPId(Integer baseId, Integer parentId) {
		return repository.findByBIdAndPId(baseId, parentId);
	}
	
	
	/**
	 * 根据内设机构ID和baseID向上移动内设机构
	 * 
	 * @param deptId
	 * @param baseId
	 * @return Map<String, String>
	 */
	public Map<String, String> moveUp(Integer deptId, Integer baseId) {
		Map<String, String> actionMsgMap = new HashMap<String,String>();
		actionMsgMap.put("msg", "对不起，向上不能移动，已达到最顶部位置。");
		
		DepartmentEntity upDeptEntity = null;
		Integer upDeptNum = null;
		DepartmentEntity  currentDeptEntity  = this.findById(deptId);
		List<DepartmentEntity> deptList = this.findByBaseId(baseId);
		
		for (int cnt = 0;  cnt < deptList.size();  cnt++) {
			// @_1  从列表中找到当前的内设机构实体
			if (deptList.get(cnt).getId() == currentDeptEntity.getId()) {
				// @_2 如果不是最顶端位置的内设机构
				if (cnt - 1 != -1)  {
					// 当前内设机构的顶端索引的内设机构
					upDeptEntity = deptList.get(cnt - 1);
					if (currentDeptEntity.getParentId() == upDeptEntity.getParentId()) {
						// @_3 当前内设机构和顶端索引的内设机构处于同级
						
						//交换两者的内设机构排序号并进行更新
						upDeptNum = upDeptEntity.getDepNum();
						upDeptEntity.setDepNum(currentDeptEntity.getDepNum());
						currentDeptEntity.setDepNum(upDeptNum);
						
						// 更新顶端索引的内设机构
						this.save(upDeptEntity);
						// 更新当前的内设机构
						this.save(currentDeptEntity);
						
						actionMsgMap.put("msg", "向上移动成功。");
						break;
					} else { 
						// @_4 当前内设机构和顶端索引的内设机构处于不同级
						 List<DepartmentEntity>   deptListPid = this.findByBIdAndPId(baseId, currentDeptEntity.getParentId());
						 for (int count = 0;  count < deptListPid.size();  count++) {
							if (deptListPid.get(count).getId() == currentDeptEntity.getId()) {
								if (count - 1 != -1) {
									// @_5 如果不是最顶端位置的内设机构
									
									upDeptEntity = deptListPid.get(count - 1);// 上一处索引的数据
									upDeptNum  = upDeptEntity.getDepNum();
									upDeptEntity.setDepNum(currentDeptEntity.getDepNum());
									currentDeptEntity.setDepNum(upDeptNum);
									
									// 更新顶端索引的内设机构
									this.save(upDeptEntity);
									// 更新当前的内设机构
									this.save(currentDeptEntity);
									
									actionMsgMap.put("msg", "向上移动成功。");
									
									break;
								} // @_5 如果不是最顶端位置的内设机构
							}
						}
					} 
				} // @_2【if】 如果不是最顶端位置的内设机构
			}  // @_1【if】  从列表中找到当前的内设机构实体
		} 
		
		 return actionMsgMap;
	}
	
	
	/**
	 * 根据内设机构ID和baseID向上移动内设机构
	 * 
	 * @param deptId
	 * @param baseId
	 * @return Map<String, String>
	 */
	public Map<String, String> moveDown(Integer deptId, Integer baseId) {
		Map<String, String> actionMsgMap = new HashMap<String,String>();
		actionMsgMap.put("msg", "对不起，向下不能移动，已达到最底部位置。");
		
		DepartmentEntity downDeptEntity = null;
		Integer downDeptNum = null;
		DepartmentEntity  currentDeptEntity  = this.findById(deptId);
		List<DepartmentEntity> deptList = this.findByBaseId(baseId);
		
		for (int cnt = 0;  cnt < deptList.size();  cnt++) {
			// @_1  从列表中找到当前的内设机构实体
			if (deptList.get(cnt).getId() == currentDeptEntity.getId()) {
				// @_2 如果不是最底部位置的内设机构
				if (cnt + 1 != deptList.size() )  {
					// 当前内设机构的底部索引的内设机构
					downDeptEntity = deptList.get(cnt + 1);
					if (currentDeptEntity.getParentId() == downDeptEntity.getParentId()) {
						// @_3 当前内设机构和底部索引的内设机构处于同级
						
						//交换两者的内设机构排序号并进行更新
						downDeptNum = downDeptEntity.getDepNum();
						downDeptEntity.setDepNum(currentDeptEntity.getDepNum());
						currentDeptEntity.setDepNum(downDeptNum);
						
						// 更新底部索引的内设机构
						this.save(downDeptEntity);
						// 更新当前的内设机构
						this.save(currentDeptEntity);
						
						actionMsgMap.put("msg", "向下移动成功。");
						break;
					} else { 
						// @_4 当前内设机构和底部索引的内设机构处于不同级
						 List<DepartmentEntity>   deptListPid = this.findByBIdAndPId(baseId, currentDeptEntity.getParentId());
						 for (int count = 0;  count < deptListPid.size();  count++) {
							if (deptListPid.get(count).getId() == currentDeptEntity.getId()) {
								if (count + 1 != deptListPid.size()) {
									// @_5 如果不是最底部位置的内设机构
									
									// 取得当前内设机构的底部索引的内设机构
									downDeptEntity = deptListPid.get(count + 1);
									downDeptNum  = downDeptEntity.getDepNum();
									downDeptEntity.setDepNum(currentDeptEntity.getDepNum());
									currentDeptEntity.setDepNum(downDeptNum);
									
									// 更新底部索引的内设机构
									this.save(downDeptEntity);
									// 更新当前的内设机构
									this.save(currentDeptEntity);
									
									actionMsgMap.put("msg", "向下移动成功。");
									
									break;
								} // @_5 如果不是最底部位置的内设机构
							}
						}
					} 
				} // @_2【if】 如果不是最顶端位置的内设机构
			}  // @_1【if】  从列表中找到当前的内设机构实体
		} 
		
		 return actionMsgMap;
	}

	/**
	 * 递归删除内设机构信息
	 * 
	 * @param deptId
	 * @return 返回删除的内设机构ID
	 */
	public List<Integer> recvDeleteByDeptId(Integer deptId) {
		List<Integer> deptIdList = new ArrayList<Integer>();
		Stack<Integer> stackDeptIds = new Stack<Integer>();
		stackDeptIds.add(deptId);
		recurFindDeptId(deptId, stackDeptIds);
		Integer temDeptId = null;
		
		while (!stackDeptIds.empty()) { 
			temDeptId = stackDeptIds.pop();
			deptIdList.add(temDeptId);
			this.delete(temDeptId);
		} 
		return deptIdList;
	}
	
	/**
	 * 根据主键ID递归取得内设机构ID
	 * @param deptId
	 * @param stackDeptIds
	 * @return void
	 */
	public  void recurFindDeptId(Integer deptId, Stack<Integer> stackDeptIds) {
	     List<DepartmentEntity> deptList = repository.findByParentIdOrderByDepNumAsc(deptId);
	     for(DepartmentEntity deptEntity : deptList){
	    	 // 避免出现递归死循环的问题将异常数据过滤掉（内设机构的ID与parentId相等的异常情况）
	    	 if(deptEntity.getId().equals(deptId)) {
	    		 continue;
	    	 }
	    	 stackDeptIds.add(deptEntity.getId());
			 recurFindDeptId(deptEntity.getId(),stackDeptIds); //递归调用取得内设机构ID
	     }
	     return;
	}
	
	/**
	 * 增加内设机构排序功能（按照排序号升序）
	 * @param deptTreeNodeList
	 * @return
	 */
	private  List<DepartmentTreeNodeVo> receiveSortDeptList(List<DepartmentTreeNodeVo> deptTreeNodeList) {
		if (null == deptTreeNodeList || deptTreeNodeList.isEmpty()) {
			return new ArrayList<DepartmentTreeNodeVo>();
		}
		Collections.sort(deptTreeNodeList, new Comparator<DepartmentTreeNodeVo>() {
			@Override
			public int compare(DepartmentTreeNodeVo o1, DepartmentTreeNodeVo o2) {
				if (null == o2.getDepNum() ) {
					return 1;
				}
				if (null == o1.getDepNum() ) {
					return -1;
				}
				if (o1.getDepNum() > o2.getDepNum()) {
					return 1;
				} else if (o1.getDepNum() < o2.getDepNum()) {
					return -1;
				} else {
					return 0;
				}
			}
		});
		// 递归排序
		for (DepartmentTreeNodeVo vo : deptTreeNodeList) {
			receiveSortDeptList(vo.getChildren());
		}
		return deptTreeNodeList;
	}
	
	/**
	 * 增加内设机构排序功能（按照排序号升序）
	 * @param deptTreeNodeList
	 * @return
	 */
	private  List<DepartmentTreeNodeVo2> receiveSortDeptList2(List<DepartmentTreeNodeVo2> deptTreeNodeList) {
		if (null == deptTreeNodeList || deptTreeNodeList.isEmpty()) {
			return new ArrayList<DepartmentTreeNodeVo2>();
		}
		Collections.sort(deptTreeNodeList, new Comparator<DepartmentTreeNodeVo2>() {
			@Override
			public int compare(DepartmentTreeNodeVo2 o1, DepartmentTreeNodeVo2 o2) {
				if (null == o2.getDepNum() ) {
					return 1;
				}
				if (null == o1.getDepNum() ) {
					return -1;
				}
				if (o1.getDepNum() > o2.getDepNum()) {
					return 1;
				} else if (o1.getDepNum() < o2.getDepNum()) {
					return -1;
				} else {
					return 0;
				}
			}
		});
		// 递归排序
		for (DepartmentTreeNodeVo2 vo : deptTreeNodeList) {
			receiveSortDeptList2(vo.getChildren());
		}
		return deptTreeNodeList;
	}
	
	//▼▼▼▼▼▼▼▼权责用DAO▼▼▼▼▼▼▼▼
	public List<DepartmentEntity> findByItemIdAndOrgId(Integer itemId,
			Integer orgId) {
		return repository.findByItemIdAndOrgId(itemId, orgId);
	}
	
	public DepartmentEntity findByCode(String depCode, Integer orgId) {
		
		List<DepartmentEntity> list = repository.findByCode(depCode, orgId);
		
		if (null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	public List<DepartmentEntity> findByCodeId(String depCode, Integer baseId) {
		List<DepartmentEntity> departList = null;
		if(StringUtils.isNotBlank(depCode)){
			departList = repository.findByCodeId2(depCode, baseId);
		} else {
			departList = repository.findByCodeId1(baseId);
		}
		
		return departList;
	}
	
	public DepartmentEntity[] findByCodes(String[] depCodes, Integer orgId) {
		int len = (depCodes != null) ? depCodes.length : 0;
		DepartmentEntity[] beans = null;
		List<DepartmentEntity> deps = new ArrayList<DepartmentEntity>();
		for (int i = 0; i < len; i++) {
			String code = depCodes[i];
			if (StringUtils.isNotBlank(code)) {
				DepartmentEntity od = findByCode(code, orgId);
				if (null != od) {
					deps.add(od);
				}
			}
		}
		beans = new DepartmentEntity[deps.size()];
		return deps.toArray(beans);
	}
	//▲▲▲▲▲▲▲▲权责用DAO▲▲▲▲▲▲▲▲
}
